#ifndef P2P_CLIENT_LOGIN_H_
#define P2P_CLIENT_LOGIN_H_

#include "start.h"

#define WIDTH 20
#define HEIGHT 5

void printMenu(WINDOW *win, char *uID, char *pwd, int uID_p, int pwd_p, int row, int col)
{
	wclear(win);
	box(win, 0, 0);
	mvwprintw(win, 1, 1, "uID:%s", uID);
	mvwprintw(win, 2, 1, "pwd:%s", pwd);
	
	if (col == 0)
	{
		wattron(win, A_REVERSE);
		mvwprintw(win, 3, 1, "REGISTER");
		wattroff(win, A_REVERSE);
	}
	else
		mvwprintw(win, 3, 1, "REGISTER");
	if (col == 1)
	{
		wattron(win, A_REVERSE);
		mvwprintw(win, 3, 13, "LOGIN");
		wattroff(win, A_REVERSE);
	}
	else
		mvwprintw(win, 3, 13, "LOGIN");
	
	if (row == 0)
		wmove(win, 1, 5 + uID_p);
	else if (row == 1)
		wmove(win, 2, 5 + pwd_p);
	else if (col == 0)
		wmove(win, 3, 9);
	else
		wmove(win, 3, 18);
	wrefresh(win);
}

int start(char *uID, char *pwd)
{
	WINDOW *loginWin;
	int startX, startY;
	int c;
	int uID_p, pwd_p;
	int row, col;
	
	initscr();
	cbreak();
	noecho();
	
	startX = (COLS - WIDTH) >> 1;
	startY = (LINES - HEIGHT) >> 1;
	
	loginWin = newwin(HEIGHT, WIDTH, startY, startX);
	keypad(loginWin, TRUE);
	refresh();
	
	uID_p = pwd_p = row = 0;
	col = 1;
	printMenu(loginWin, uID, pwd, uID_p, pwd_p, row, col);
	
	while (1)
	{
		c = wgetch(loginWin);
		if (c == KEY_UP)
			row = (row + 2) % 3;
		else if (c == KEY_DOWN)
			row = (row + 1) % 3;
		else if (c == 127)	//KEY_BACKSPACE
		{
			if (row == 0)
			{
				if (uID_p != 0)
					uID[--uID_p] = 0;
			}
			else if (row == 1)
			{
				if (pwd_p != 0)
					pwd[--pwd_p] = 0;
			}
		}
		else if (c == KEY_LEFT || c == KEY_RIGHT)
		{
			if (row == 2)
				col = !col;
		}
		else if (c == 343)	//KEY_ENTER
		{
			refresh();
			endwin();
			return col;
		}
		else
		{
			if (row == 0)
			{
				if (uID_p < LEN)
					uID[uID_p++] = c;
			}
			else if (row == 1)
			{
				if (pwd_p < LEN)
					pwd[pwd_p++] = c;
			}
		}
//		mvprintw(10, 1, "press %d", c);
//		refresh();
		printMenu(loginWin, uID, pwd, uID_p, pwd_p, row, col);
	}
}

#endif
